package com.smartstate.admin.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smartstate.admin.biz.entity.dto.SyslogSearchDto;
import com.smartstate.admin.biz.entity.vo.SyslogVo;
import com.smartstate.admin.biz.mapper.ApiLoggerMapper;
import com.smartstate.admin.biz.service.ApiLoggerService;
import com.smartstate.common.base.entity.supperAdmin.Syslog;
import com.smartstate.common.base.exception.CommonException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ApiLoggerServiceImpl extends ServiceImpl<ApiLoggerMapper, Syslog> implements ApiLoggerService {

    @Override
    public IPage<SyslogVo> queryApiLoggerList(SyslogSearchDto param) {
        Integer currentPage = param.getCurrent() == null ? 1 : param.getCurrent();
        Integer pageSize = param.getPageSize() == null ? 10 : param.getPageSize();
        Page<SyslogVo> result = new Page<>(currentPage, pageSize);
        Page<Syslog> page = new Page<>(currentPage, pageSize);
        QueryWrapper<Syslog> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(param.getUserName()), "USER_NAME", param.getUserName());
        queryWrapper.like(StringUtils.isNotBlank(param.getMethod()), "METHOD", param.getMethod());
        queryWrapper.like(StringUtils.isNotBlank(param.getMethodName()), "METHOD_NAME", param.getMethodName());
        queryWrapper.ge(null != param.getStartTime(), "CREATE_TIME", param.getStartTime());
        queryWrapper.le(null != param.getEndTime(), "CREATE_TIME", param.getEndTime());
        queryWrapper.orderByDesc("CREATE_TIME");
        IPage<Syslog> iPage = baseMapper.selectPage(page, queryWrapper);
        BeanUtils.copyProperties(iPage, result);
        return result.setRecords(new SyslogVo().buildVoList(iPage.getRecords()));
    }

    @Transactional(rollbackFor = CommonException.class)
    @Override
    public boolean deleteApiLogger(String id) {
        return baseMapper.deleteById(id) > 0;
    }

    @Transactional(rollbackFor = CommonException.class)
    @Override
    public boolean deleteBatchApiLogger(List<String> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public boolean saveLog(Syslog syslog) {
        return baseMapper.insert(syslog) > 0;
    }
}
